<template>
  <basic-container>
    <el-row>
      <el-col :span="8">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          v-model="form"
          ref="crud"
          @row-click="rowClick"
          @search-change="searchChange"
          @search-reset="searchReset"
          @refresh-change="refreshChange"
          @on-load="onLoad"
          :before-close="beforeClose"
        >
        </avue-crud>
      </el-col>
      <el-col :span="16">
        <el-tabs type="border-card" style="margin: 10px" v-if="isShowDetailTable">
          <el-tab-pane label="扩展属性配置详情">
            <avue-crud
              :option="detailOption"
              :table-loading="detailLoading"
              :data="detailData"
              :permission="permissionList"
              :before-open="beforeOpen"
              ref="detailCrud"
              @row-update="detailUpdate"
              @row-save="detailSave"
              @row-del="detailDel"
              @selection-change="selectionDetailChange"
              @refresh-change="detailRefreshChange"
            >
              <template slot="menuLeft">
                <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.customAttributeConfig_add && this.detailOptionAddBtn" @click="openAddDialog"
                  >新 增
                </el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.customAttributeConfig_delete && this.detailOptionAddBtn" @click="detailHandleDelete"
                  >删 除
                </el-button>
                <span v-if="this.detailConfigId" style="margin-left: 10px">名称：{{ this.packingName }}</span>
              </template>
              <!-- <template slot-scope="{ row }" slot="isOutPack">
            <el-tag>{{ row.isOutPack === false ? '否' : '是' }}</el-tag>
          </template> -->
              <template slot-scope="{ row }" slot="isWeight">
                <el-tag :class="row.isWeight ? 'successTag' : 'dangerTag'">{{ row.isWeight === false ? '否' : '是' }}</el-tag>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <!-- <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template> -->
    <el-dialog append-to-body title="选择扩展属性" :visible.sync="openAttributeDialog" top="5vh">
      <div class="sail-header-dialog-content">
        <avue-crud
          v-if="openAttributeDialog"
          :option="attributeOption"
          :table-loading="attributeLoading"
          :page.sync="attributePage"
          :data="attributeData"
          ref="attributeCrud"
          @row-click="attributeRowClick"
          @search-change="attributeSearchChange"
          @search-reset="attributeSearchReset"
          @selection-change="selectionAttributeChange"
          @refresh-change="attributeRefreshChange"
          @on-load="onAttributeLoad"
        >
        </avue-crud>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="selectAttribute">选 择</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="openAttributeDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog append-to-body title="属性编辑" :visible.sync="stagingDetailDialog">
      <avue-crud
        :option="stagingDetailOption"
        :data="stagingDetailData"
        :before-open="beforeOpen"
        ref="stagingDetailCrud"
        @row-update="stagingDetailUpdate"
        @row-del="stagingDetailDel"
      >
        <template slot-scope="{ row }" slot="isWeight">
          <el-tag :class="row.isWeight ? 'successTag' : 'dangerTag'">{{ row.isWeight === false ? '否' : '是' }}</el-tag>
        </template>
      </avue-crud>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitstagingDetail">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="stagingDetailDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script>
import { getList, add, remove, getPagePathList, getAttributeConfig } from '@/api/system/custom-attribute-config';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      isSubitem: false, //是否新增子项
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      selectionList: [],
      packingQuantity: '',
      option: {
        height: 'calc(100vh - 367px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 12,
        searchMenuSpan: 12,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: true,
        menu: false,
        selection: false,
        dialogClickModal: false,
        labelWidth: 130,
        highlightCurrentRow: true, // 选中高亮
        dialogWidth: '30%',
        column: [
          {
            label: '菜单名称',
            prop: 'dictValue',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入菜单名称',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: [],
      selectPage: {},
      tableOption: {}, //公用模态框配置信息
      detailLoading: false,
      dialogTitle: '新增',
      showDialog: false,
      detailData: [],
      selectionDetailList: [],
      detailOptionAddBtn: false,
      detailOption: {
        //包装详情列表内容配置
        height: 'calc(100vh - 287px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 150,
        column: [
          {
            label: '名称',
            prop: 'lableCnName',
            width: 150,
            rules: [
              {
                required: true,
                message: '请选择名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'attributeKey',
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          // {
          //   label: '是否显示在列表',
          //   prop: 'isShowed',
          //   type: 'switch',
          //   dicData: [
          //     {
          //       label: '否',
          //       value: false
          //     },
          //     {
          //       label: '是',
          //       value: true
          //     }
          //   ],
          //   value: false
          // },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      modalName: '',
      stagingDetailDialog: false,
      stagingDetailOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: true,
        delBtn: true,
        selection: false,
        dialogClickModal: false,
        column: [
          {
            label: '名称',
            prop: 'lableCnName',
            width: 150,
            rules: [
              {
                required: true,
                message: '请选择名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'attributeKey',
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          // {
          //   label: '是否显示在列表',
          //   prop: 'isShowed',
          //   type: 'switch',
          //   dicData: [
          //     {
          //       label: '否',
          //       value: false
          //     },
          //     {
          //       label: '是',
          //       value: true
          //     }
          //   ],
          //   value: false
          // },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      stagingDetailData: [],
      openAttributeDialog: false,
      attributeLoading: false,
      attributeOption: {
        height: 350,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: false,
        column: [
          {
            label: '属性名称',
            prop: 'lableCnName',
            width: 150,
            search: true
          },
          {
            label: '编码',
            prop: 'attributeKey',
            search: true
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '属性类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datatime'
              }
            ]
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '是否显示',
            prop: 'isShowed',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      attributeData: [],
      attributePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      attributeQuery: {},
      selectionAttributeList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.customAttributeConfig_add, false),
        delBtn: this.vaildData(this.permission.customAttributeConfig_delete, false),
        editBtn: this.vaildData(this.permission.customAttributeConfig_edit, false)
      };
    },
    detailIds() {
      console.log(this.selectionDetailList);
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      console.log(ids);
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      this.isShowDetailTable = true;
    });
  },
  watch: {},
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      this.query = params;
      this.onLoad();
      done();
    },
    refreshChange() {
      this.onLoad();
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        const attributeKey = this.findObject(this.detailOption.column, 'attributeKey');
        attributeKey.disabled = true;
        const controlType = this.findObject(this.detailOption.column, 'controlType');
        controlType.disabled = true;
      }
      done();
    },
    onLoad() {
      this.loading = true;
      getPagePathList('custom_attribute_config_menu').then((res) => {
        this.data = res.data.data;
        if (this.query.dictValue) {
          let list = [];
          this._forEach(this.data, (item) => {
            if (item.dictValue.includes(this.query.dictValue)) {
              list.push(item);
            }
          });
          this.data = list;
        }
        this.loading = false;
        this.detailOption.addBtn = false;
        this.detailData = [];
      });
    },
    /**
     * 单击事件
     */
    rowClick(row) {
      this.selectPage = row;
      this.onDetailLoad();
    },
    detailUpdate(row, index, done, loading) {
      add([row]).then(
        () => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    detailDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    detailHandleDelete() {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.detailIds);
        })
        .then(() => {
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    /**
     * 查询包装配置详情
     */
    onDetailLoad() {
      this.detailLoading = true;
      getList(this.selectPage.dictKey).then((res) => {
        const data = res.data.data;
        this.detailData = data;
        this.detailOptionAddBtn = true;
        this.detailLoading = false;
        this.selectionDetailClear();
      });
    },
    detailRefreshChange() {
      this.onDetailLoad();
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      this.$refs.detailCrud.toggleSelection();
    },
    openAddDialog() {
      this.openAttributeDialog = true;
    },
    /**
     * 获取选择的模态框行数据
     */
    selectAttribute() {
      if (this.selectionAttributeList.length === 0) {
        this.$message.warning('请至少选择一条数据！');
        return;
      }
      this.stagingDetailDialog = true;
      this._forEach(this.selectionAttributeList, (item) => {
        item['attributeId'] = item.id;
        delete item.id;
        item.pagePath = this.selectPage.dictKey;
        item.pageName = this.selectPage.dictValue;
      });
      this.stagingDetailData = this._cloneDeep(this.selectionAttributeList);
    },
    stagingDetailUpdate(row, index, done, loading) {
      this.$set(this.stagingDetailData, [index], row);
      done();
    },
    stagingDetailDel(row, index) {
      this.stagingDetailData.splice(index, 1);
    },
    submitstagingDetail() {
      if (this.stagingDetailData.length === 0) {
        this.$message.warning('数据不能为空！');
        return;
      }
      let attributeKeyList = [];
      this._forEach(this.detailData, (item) => {
        this._forEach(this.stagingDetailData, (rowDataItem) => {
          if (item.attributeKey === rowDataItem.attributeKey) {
            attributeKeyList.push(rowDataItem.attributeKey);
          }
        });
      });
      if (attributeKeyList.length > 0) {
        this.$message.error(`列表中已存在如下编码${attributeKeyList.join('，')}的属性`);
        return;
      }
      this._forEach(this.stagingDetailData, (item) => {
        item['pageCode'] = item.pagePath;
      });
      add(this.stagingDetailData).then(
        () => {
          this.stagingDetailDialog = false;
          this.openAttributeDialog = false;
          this.onDetailLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (error) => {}
      );
    },
    onAttributeLoad(page, params = {}) {
      this.attributeLoading = true;
      getAttributeConfig(page.currentPage, page.pageSize, Object.assign(params, this.attributeQuery)).then((res) => {
        const data = res.data.data;
        this.attributePage.total = data.total;
        this.attributeData = data.records;
        this.attributeLoading = false;
      });
    },
    attributeRefreshChange() {
      this.onAttributeLoad(this.attributePage);
    },
    attributeRowClick(row) {
      if (this.attributeOption.selection) {
        this.$refs.attributeCrud.toggleRowSelection(row);
      }
    },
    attributeSearchChange(params, done) {
      this.attributeQuery = params;
      this.onAttributeLoad(this.attributePage);
      done();
    },
    attributeSearchReset() {
      this.attributeQuery = {};
      this.onAttributeLoad(this.attributePage);
    },
    selectionAttributeChange(list) {
      this.selectionAttributeList = list;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
